package cn.diancan.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.diancan.dao.MyBaseDao;
import cn.diancan.exception.OutMsgException;
import cn.diancan.model.Goods;
import cn.diancan.model.GoodsCategory;
import cn.diancan.model.types.CommonConstant;
import cn.diancan.model.types.CommonType;
import cn.diancan.service.GoodsCategoryService;
import cn.diancan.util.DateUtil;
import cn.diancan.vo.model.GoodsCategoryVo;
import cn.diancan.vo.other.Pager;
import cn.diancan.vo.other.ResultVoUtil;

@Component("goodsCategoryService")
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    @Resource(name = "MyBaseDao")
    private MyBaseDao<GoodsCategory> goodsCategoryDao;


    @Resource(name = "MyBaseDao")
    private MyBaseDao<Goods> goodsDao;

    @Override
    public GoodsCategory saveGoodsCategory(Long parentId, String categoryName, Integer isCanDiscount) throws OutMsgException, Exception {
        if (null == categoryName || "".equals(categoryName.trim())) {
            throw new OutMsgException("分类名不能为空");
        }


        GoodsCategory goodsCategory = new GoodsCategory();
        goodsCategory.setParentId(null);
        goodsCategory.setLevel(1);
        if (null != parentId && parentId > 0) {
            GoodsCategory parentGoodsCategory = findGoodsCategoryById(parentId);
            if (null != parentGoodsCategory) {
                if (parentGoodsCategory.getLevel() >= CommonConstant.MAX_GOODS_CATEGORY_LEVEL) {
                    throw new OutMsgException("产品分类等级最大" + CommonConstant.MAX_GOODS_CATEGORY_LEVEL + "级");
                }
                goodsCategory.setParentId(parentGoodsCategory.getId());
                goodsCategory.setLevel(parentGoodsCategory.getLevel() + 1);
            }
        }

        if (goodsCategory.getLevel().equals(1)) {
            GoodsCategory goodsCategoryTemp = findGoodsCategoryName(categoryName, null, goodsCategory.getLevel());
            if (null != goodsCategoryTemp) {
                throw new OutMsgException("不能建立相同的名称分类");
            }
        } else if (goodsCategory.getLevel().equals(2)) {
            GoodsCategory goodsCategoryTemp = findGoodsCategoryName(categoryName, goodsCategory.getParentId(), goodsCategory.getLevel());
            if (null != goodsCategoryTemp) {
                throw new OutMsgException("不能建立相同的名称分类");
            }
        }
        goodsCategory.setIsHide(CommonType.Hide.NO);
        goodsCategory.setIndexNo(0);
        goodsCategory.setIsCanDiscount(isCanDiscount);
        goodsCategory.setCategoryName(categoryName);
        goodsCategory.setCreateTime(DateUtil.currentDateTime());
        goodsCategory.setModifyTime(DateUtil.currentDateTime());
        goodsCategory.setIsDelete(CommonType.Delete.NO);
        goodsCategoryDao.save(goodsCategory);
        return goodsCategory;
    }


    @Override
    public boolean updateGoodsCategory(Long goodsCategoryId, Long parentId, String categoryName, Integer isCanDiscount) throws OutMsgException, Exception {
        if (null == categoryName || "".equals(categoryName.trim())) {
            throw new OutMsgException("分类不能为空");
        }
        GoodsCategory goodsCategory = findGoodsCategoryById(goodsCategoryId);
        if (null == goodsCategory) {
            throw new OutMsgException("产品分类不存在");
        }

        goodsCategory.setParentId(null);
        goodsCategory.setLevel(1);
        if (null != parentId) {
            GoodsCategory parentGoodsCategory = findGoodsCategoryById(parentId);
            if (null != parentGoodsCategory) {
                if (parentGoodsCategory.getLevel() >= CommonConstant.MAX_GOODS_CATEGORY_LEVEL) {
                    throw new OutMsgException("产品分类等级最大" + CommonConstant.MAX_GOODS_CATEGORY_LEVEL + "级");
                }
                goodsCategory.setParentId(parentGoodsCategory.getId());
                goodsCategory.setLevel(parentGoodsCategory.getLevel() + 1);
            }
        }

        goodsCategory.setIsCanDiscount(isCanDiscount);
        goodsCategory.setCategoryName(categoryName);
        goodsCategory.setModifyTime(DateUtil.currentDateTime());
        goodsCategoryDao.update(goodsCategory);

        return true;
    }


    @Override
    public GoodsCategory findGoodsCategoryById(Long goodsCategoryId) throws OutMsgException {
        if (null == goodsCategoryId) {
            throw new OutMsgException("参数错误");
        }
        return goodsCategoryDao.get("FROM GoodsCategory WHERE id=? AND isDelete=?", new Object[]{goodsCategoryId, CommonType.Delete.NO});
    }

    @Override
    public Pager findByPager(Pager pager, String categoryName) throws OutMsgException {
        String hql = "FROM GoodsCategory WHERE isDelete=? ";
        List<Object> param = new ArrayList<Object>();
        param.add(CommonType.Delete.NO);
        if (null != categoryName && !"".equals(categoryName.trim())) {
            hql += " AND instr(categoryName,?)>0 ";
            param.add(categoryName.trim());
        }

        List<GoodsCategory> goodsCategorys = goodsCategoryDao.find(hql, param, pager.getPageNumber(), pager.getPageSize());
        Long count = goodsCategoryDao.count("SELECT count(id) " + hql, param);
        pager.setList(goodsCategorys);
        pager.setTotalCount(count.intValue());

        return pager;
    }

    /**
     * private Long id;
     * <p>
     * private String categoryName;
     * private Long parentId;
     * private Integer level;
     * <p>
     * <p>
     * private Long goodsCategoryId;
     * private Long parentCategoryId;
     * private String parentCategoryName;
     */

    @Override
    public Pager findVoByPager(Pager pager, Long goodsCategoryParentId, String categoryName) throws OutMsgException {
        String hql_pre = "SELECT g1.id,g1.categoryName,g1.parentId,g1.isCanDiscount,g1.level,g1.id AS goodsCategoryId,g1.parentId AS parentCategoryId,g2.categoryName AS parentCategoryName";
        String hql = " FROM GoodsCategory AS g1 LEFT JOIN GoodsCategory AS g2 ON g1.parentId=g2.id ";
        hql += " WHERE g1.isDelete=? AND g1.isHide=? ";

        List<Object> param = new ArrayList<Object>();
        param.add(CommonType.Delete.NO);
        param.add(CommonType.Hide.NO);

        if (null != categoryName && !"".equals(categoryName.trim())) {
            hql += " AND instr(g1.categoryName,?)>0 ";
            param.add(categoryName.trim());
        }
        if (null != goodsCategoryParentId && goodsCategoryParentId > 0) {
            hql += " AND g1.parentId=? ";
            param.add(goodsCategoryParentId);
        }

        List<Object[]> lsObj = goodsCategoryDao.findSql(hql_pre + hql, param, pager.getPageNumber(), pager.getPageSize());
        BigInteger count = (BigInteger) goodsCategoryDao.countSQL("SELECT count(g1.id) " + hql, param.toArray(new Object[]{}));
        List<GoodsCategoryVo> goodsCategorys = ResultVoUtil.object2Model(GoodsCategoryVo.class, lsObj, hql_pre + hql);

        pager.setList(goodsCategorys);
        pager.setTotalCount(count.intValue());

        return pager;
    }


    @Override
    public boolean deleteGoodsCategoryById(Long id) throws OutMsgException, Exception {
        GoodsCategory goodsCategory = findGoodsCategoryById(id);
        if (null == goodsCategory) {
            throw new OutMsgException("该产品分类不存在");
        }


        //判断是否有子分类
        GoodsCategory goodsCategory1 = goodsCategoryDao.get("FROM GoodsCategory WHERE parentId=? AND isDelete=?", new Object[]{id, CommonType.Delete.NO});
        if (null != goodsCategory1) {
            throw new OutMsgException("错误操作:该产品分类还有子分类");
        }


        //判断产品是否引用

        Goods goods = goodsDao.get("FROM Goods WHERE goodsCategoryId=? AND isDelete=?", new Object[]{id, CommonType.Delete.NO});
        if (null != goods) {
            throw new OutMsgException("错误操作:该产品分类下还有商品");
        }

        goodsCategory.setIsDelete(CommonType.Delete.YES);
        goodsCategoryDao.update(goodsCategory);

        return true;
    }


    @Override
    public GoodsCategory findGoodsCategoryName(String categoryName, Long parentId, Integer level) throws OutMsgException {
        String hql = "FROM GoodsCategory WHERE isDelete=? AND categoryName=? ";
        List<Object> param = new ArrayList<Object>();
        param.add(CommonType.Delete.NO);
        param.add(categoryName.trim());


        if (null != level && (level.equals(1) || level.equals(2))) {
            hql += " AND level=?";
            param.add(level);
        }
        if (null != parentId) {
            hql += " AND parentId=?";
            param.add(parentId);
        }


        return goodsCategoryDao.get(hql, param);
    }


    @Override
    public List<GoodsCategory> findGoodsCategoryList(Long goodsCategoryParentId, Integer pageNo, Integer row) {
        String hql = "FROM GoodsCategory WHERE isDelete=? ";
        List<Object> param = new ArrayList<Object>();
        param.add(CommonType.Delete.NO);


        if (null != goodsCategoryParentId && goodsCategoryParentId > 0) {
            hql += " AND parentId=? ";
            param.add(goodsCategoryParentId);
        } else {
            hql += " AND level=? ";
            param.add(1);
        }


        List<GoodsCategory> list = goodsCategoryDao.find(hql, param, pageNo, row);
        return list;
    }

    @Override
    public GoodsCategory findByGoodsCategoryName(String categoryName) throws OutMsgException, Exception {
        if(null==categoryName){
            throw new OutMsgException("参数错误");
        }

        GoodsCategory goodsCategory = goodsCategoryDao.get("FROM GoodsCategory WHERE categoryName=? AND isDelete=?",
                new Object[]{categoryName ,CommonType.Delete.NO});


        return goodsCategory;
    }
}
